import { ref } from 'vue'
import Sortable from 'sortablejs'
import { articleSort } from '@/api/article'
import { ElMessage } from 'element-plus'
import i18n from '@/i18n'
export const tableRef = ref(null)

export const initSortable = (tabbleData, cb) => {
  const el = tableRef.value.$el.querySelector(
    '.el-table__body-wrapper > table > tbody'
  )

  Sortable.create(el, {
    ghostClass: 'sortable-ghost',
    onEnd: async (event) => {
      const { oldIndex, newIndex } = event
      await articleSort({
        initRanking: tabbleData.value[oldIndex].ranking,
        finalRanking: tabbleData.value[newIndex].ranking
      })
      tabbleData.value = []
      cb && cb()
      ElMessage.success({
        message: i18n.global.t('message.article.sortSuccess'),
        type: 'success'
      })
    }
  })
}
